clc;
close all;
clear all;
global B_N R l sigma NETWORK_SIZE referenceDistance referenceLoss txPower threshold alpha Noise SNR_Margin ETX_Threshold;
B_N = 2000; 
R = 250*8; 
l = 5; 
sigma = 5;

referenceDistance = 1;
referenceLoss = 46.6777;
txPower = -25;
threshold = -85.0590;
alpha = 2.6;
Noise = 10*log10(4.01237e-13) + 30;
SNR_Margin = 2; %dB
ETX_Threshold = 1/0.72;


NetworkMatrix = importdata('data.txt');
[p q] = size(NetworkMatrix);
NETWORK_SIZE = p;
EtxMatrix=zeros(NETWORK_SIZE,NETWORK_SIZE);
for i=1:NETWORK_SIZE
    for j=1:NETWORK_SIZE
        if i==j
           EtxMatrix(i,j)=100000;
        else
            distance = sqrt((NetworkMatrix(i,1) - NetworkMatrix(j,1))^2 + (NetworkMatrix(i,2) - NetworkMatrix(j,2))^2);
            rx_power = CalculateRxPower(distance, alpha);
            PDR = SnrToPdr(realpow (10, (rx_power - Noise - SNR_Margin)/10), 126);
            EtxMatrix(i,j) = 1/PDR;
        end
    end
end
EtxMatrix (find (EtxMatrix > ETX_Threshold)) = 1000000;
[ETXDist, Parent] = Dijkstra (EtxMatrix, 1, NETWORK_SIZE);
PdrRequirementMatrix = zeros(NETWORK_SIZE,1);
for i = 1: NETWORK_SIZE
    if isnan ( Parent(i))
        PdrRequirementMatrix(i) = 1/100000;
    else
        PdrRequirementMatrix(i) = 1/EtxMatrix (i, Parent(i));
    end
end
%Parent = 0 means no parent since there is no node in the network with node
%id 0.
Parent(find(isnan(Parent)))=0;
fileId_Parent = fopen('parent.txt', 'w');
fprintf( fileId_Parent, '%d\n', Parent);
fclose (fileId_Parent);
fileId_LinkRequirement = fopen('link_requirement.txt','w');
fprintf( fileId_LinkRequirement, '%2.6f\n', PdrRequirementMatrix);
fclose (fileId_LinkRequirement);